<?php
	/**
	 * Nguoi tao: Phuongtt
	 * ngay tao: 27/12/2010
	 */
// Dinh nghia duong dan den thu vien cua Zend
	set_include_path('../../library/'
			. PATH_SEPARATOR . '../../application/models/'
			. PATH_SEPARATOR . '../../config/');			
	// Goi class Zend_Load
	include "../../library/Zend/Loader.php";		
	Zend_Loader::loadClass('Efy_DB_Connection');
	Zend_Loader::loadClass('Efy_Init_Config');
	Zend_Loader::loadClass('Zend_Config_Ini');
	Zend_Loader::loadClass('Zend_Registry');
	Zend_Loader::loadClass('Efy_Function_RecordFunctions');
	Zend_Loader::loadClass('Efy_Library');
	Zend_Loader::loadClass('Zend_Config_Xml');
	$conn = new Efy_DB_Connection();
	$sConfig = new Efy_Init_Config();
	//Ket noi CSDL SQL theo kieu ADODB
	$connectSQL = new Zend_Config_Ini('../../config/config.ini','dbmssql');
	$registry = Zend_Registry::getInstance();
	$registry->set('connectSQL', $connectSQL);
	$connAdo = Efy_Db_Connection::connectADO($connectSQL->db->adapter,$connectSQL->db->config->toArray());
	//Khoi tao session
	session_start();
	//Lay ten ham thuc hien
	$sFunctionName = $_REQUEST['FuntionName'];
	if($sFunctionName != '' && $sFunctionName != null){	
		$sFunctionName .= '();';
		eval($sFunctionName);
	}
	//Lay danh sach don vi theo tinh thanh, quan huyen, khoi don vi
	function getTransactionUnit(){
		global $conn;
		isset($_REQUEST['province'])?$province = $_REQUEST['province']:$province = '';
		isset($_REQUEST['district'])?$district = $_REQUEST['district']:$district = '';
		isset($_REQUEST['groupUnit'])?$groupUnit = $_REQUEST['groupUnit']:$groupUnit = '';
		$tagNameList = '';
		$tagValueList = '';
		if ($province != ''){
			$tagNameList .= 'tinh_thanh;';
			$tagValueList .= $province . ';';
		}
		if ($district != ''){
			$tagNameList .= 'quan_huyen;';
			$tagValueList .= $district . ';';
		}
		if ($district != ''){
			$tagNameList .= 'khoi_dv;';
			$tagValueList .= $groupUnit . ';';
		}
		if ($tagNameList != ''){
			$tagNameList = substr($tagNameList, 0, strlen($tagNameList) - 1);
			$tagValueList = substr($tagValueList, 0, strlen($tagValueList) - 1);
		}
		$objFunction  = new Efy_Function_RecordFunctions();
		$arrResult = $objFunction->getListByTagNameList('DM_DON_VI_THAM_GIA_BHXH',$tagNameList, $tagValueList);
		echo json_encode($arrResult); die;
	}	
	/**
	 * Creater:HUNGVM
	 * Date: 15/12/2011
	 * Idea: Tạo phương thức lấy thông tin đơn vị tham gia BHXH	 
	 */
	function getUnitInsurance(){
		//global $conn;
		isset($_REQUEST['province'])?$province = $_REQUEST['province']:$province = '';
		isset($_REQUEST['district'])?$district = $_REQUEST['district']:$district = '';
		isset($_REQUEST['groupUnit'])?$groupUnit = $_REQUEST['groupUnit']:$groupUnit = '';
		isset($_REQUEST['fullTextSearch'])?$fullTextSearch = $_REQUEST['fullTextSearch']:$fullTextSearch = '';
		$tagNameList = '';
		$tagValueList = '';
		if ($province != ''){
			$tagNameList .= 'tinh_thanh;';
			$tagValueList .= $province . ';';
		}
		if ($district != ''){
			$tagNameList .= 'quan_huyen;';
			$tagValueList .= $district . ';';
		}
		if ($groupUnit != ''){
			$tagNameList .= 'khoi_dv;';
			$tagValueList .= $groupUnit . ';';
		}
		if ($fullTextSearch != ''){
			$tagNameList .= 'c_code;';
			$tagValueList .= $fullTextSearch . ';';		
		}
		if ($tagNameList != ''){
			$tagNameList = substr($tagNameList, 0, strlen($tagNameList) - 1);
			$tagValueList = substr($tagValueList, 0, strlen($tagValueList) - 1);
		}			
		$objFunction  = new Efy_Function_RecordFunctions();
		$arrResult = $objFunction->getListByTagNameList('DM_DON_VI_THAM_GIA_BHXH',$tagNameList, $tagValueList,"",2);		
		
		$delimitor = "!~~!";//Lay ky tu phan cach giua cac phan tu
		//Hien thi cac cot cua bang hien thi du lieu
		$StrHeader = explode("!~~!",Efy_Publib_Library::_GenerateHeaderTable("5%" 
		. $delimitor . "20%" 
		. $delimitor . "73%" 
		,'<input optional = "true" type="checkbox" name="chk_all_item_id" value="" onclick="checkbox_all_item_id(document.forms[0].chk_item_id);">' 
		. $delimitor . "Mã đơn vị"
		. $delimitor . "Tên đơn vị"  
		,$delimitor));?>										
		<table cellpadding="0" width="100%" cellspacing="0" border="0" align="center" class="list-table-data" id="table-data"><?php	
				echo $StrHeader[1]; //Hien thi <col width = 'xx'><...				
				//Dinh nghia URL
				$sUrlView  = "";
				$v_current_style_name = "round_row";									
				for($index = 0;$index < sizeof($arrResult);$index++){
					$sCode = $arrResult[$index]['C_CODE'];
					$sName = $arrResult[$index]['C_NAME'];																																			
					if ($v_current_style_name == "odd_row"){
						$v_current_style_name = "round_row";
					}else{
						$v_current_style_name = "odd_row";					
					}?>					
					<tr class="<?=$v_current_style_name?>">	
						<td align="center"  class="normal_label">
							<input type="checkbox" id="chk_item_id" name="chk_item_id" value="<?=$sCode;?>" onclick="selectRowUnitInsurance(this)">											
						</td>
						<td align="center" class="normal_label" ><?=$sCode?></td>													
						<td align="left" class="normal_label"><?=$sName?></td>
					</tr><?php
				}					
				//Tu dien cac dong trang trong truong hop du lieu tra ve < so row _CONST_NUMBER_OF_ROW_PER_LIST		
				if(sizeof($arrResult) < 15){	
					echo Efy_Publib_Library::_addEmptyRow(1,20 - sizeof($arrResult),$v_current_style_name,3);		
				}?>										
		</table><?php
	}
	/**
	 * Creater: HUNGVM
	 * Date: 12/01/2009
	 * 
	 * @Idea: Thay the ky tu dac biet trong xau XML
	 *
	 * @param $psHtml : Xau can thay the
	 * @return CHuoi duoc thay the cac ky tu dac biet
	 */
	function _replaceXmlBadChar($psHtml){
		//$psHtml = stripslashes($psHtml);
		$psHtml = str_replace('&',' - ',$psHtml);
		$psHtml = str_replace('"','',$psHtml);
		$psHtml = str_replace('<','',$psHtml);
		$psHtml = str_replace('>','',$psHtml);
		$psHtml = str_replace("'",'', $psHtml);
		$psHtml = str_replace("*",'', $psHtml);
		$psHtml = str_replace("NULL",'', $psHtml);
		return $psHtml;
	}
	/**
	 * Creater:HUNGVM
	 * Date: 15/12/2011
	 * Idea: Tạo phương thức Import dữ liệu	 
	 */
	function ImportData(){
		global $conn;				
		isset($_REQUEST['recordtypeId'])?$sRecordtypeId = $_REQUEST['recordtypeId']:$sRecordtypeId = '';
		isset($_REQUEST['DataFileAttach'])?$sDataFileAttach = $_REQUEST['DataFileAttach']:$sDataFileAttach = '';
		isset($_REQUEST['ParentOwnerCode'])?$sParentOwnerCode = $_REQUEST['ParentOwnerCode']:$sParentOwnerCode = '';
		isset($_REQUEST['OwnerCode'])?$sOwnerCode = $_REQUEST['OwnerCode']:$sOwnerCode = '';
		isset($_REQUEST['ListTypeCode'])?$sListTypeCode = $_REQUEST['ListTypeCode']:$sListTypeCode = '';
		//echo utf8_encode("Long Biên");exit;
		//Lay duong dan file dinh can Import			
		$sPath = $_SERVER['SCRIPT_FILENAME'];
		$sPath = substr($sPath, 0, -21);		
		$sFileToInclude = str_replace("/", "\\", $sPath) . "attach-file\\TempUpload\\" . $sDataFileAttach;	
		//Goi class xu ly doc file Excel		
		Zend_Loader::loadClass('Efy_Publib_Excel_reader');
		$objExcelReader = new Efy_Publib_Excel_reader();
		$objExcelReader->setOutputEncoding('utf-8');
		$objExcelReader->read($sFileToInclude);		
		/*
		1=>madvi		2=>tendvi		3=>tentat		4=>tendvicq		5=>diachi	
		6=>sodkkd		7=>ngaydk		8=>mst			9=>lhdn			10=>dienthoai	
		11=>fax			12=>email		13=>taikhoan	14=>nguoilh		15=>makhoi	
		16=>tyle_bhxh	17=>tyle_bhyt	18=>tyle_tudv	19=>hsl			20=>lvnd	
		21=>lnte		22=>quidoi		23=>ma_nte		24=>madvikcb	25=>makhoikcb	
		26=>ma_dt		27=>denso		28=>ma_tinh		29=>ma_huyen	30=>ma_xa	
		31=>mavung		32=>nstn		33=>dsnv		34=>dsnvst		35=>dsnvxd	
		36=>manv		37=>ngaybd		38=>lydobd		39=>ngaykt		40=>lydokt	
		41=>dvtu		42=>ktl			43=>tattoan		44=>intendvi	45=>chon	
		46=>ghichu		47=>ma_quan
		*/
		$arrSelectColumn = array(1,2,5,10,15,28,33,34,47);
		$arrListColumn = array();		
		for($col=1;$col<=$objExcelReader->sheets[0]['numCols'];$col++){			
			if (in_array($col, $arrSelectColumn)){				
				$arrListColumn[$col] = $objExcelReader->sheets[0]['cells'][1][$col];
			}				
		}
		//var_dump($arrListColumn);
		$sXmlData = '<?xml version="1.0"?><root><data_list><records>';	
		//row = 1 thể hiện tiêu đề các cột
		for($row=2; $row<=$objExcelReader->sheets[0]['numRows']; $row++){	
			$sXmlStrTemp = '<record ';						
			for($col=1; $col<=$objExcelReader->sheets[0]['numCols']; $col++){
				if (in_array($col, $arrSelectColumn)){
					//if ($col == 5){
					//	$sXmlStrTemp .= $arrListColumn[$col] . '="' . (_replaceXmlBadChar($objExcelReader->sheets[0]['cells'][$row][$col])) . '" ';
					//}else{
						$sXmlStrTemp .= $arrListColumn[$col] . '="' . (_replaceXmlBadChar($objExcelReader->sheets[0]['cells'][$row][$col])) . '" ';
					//}										
				}											
			}		
			$sXmlStrTemp .= '/>';		
			$sXmlData .= $sXmlStrTemp;	
		}	
		$sXmlData .= '</records></data_list></root>';
		$sql = "Exec dbo.EfyLib_ImportData ";
		$sql .= "'" . $sParentOwnerCode . "'";		
		$sql .= ",'" . $sOwnerCode . "'";
		$sql .= ",'" . $sXmlData . "'";
		$sql .= ",'" . $sListTypeCode . "'";
		//echo $sql;exit;
		try {														
			$arrResult = $conn->adodbQueryDataInNameMode($sql);	
			$sMsg = $arrResult['MSG'];				
		}catch (Exception $e){						
			$sMsg = "ERROR";
		};	
		//Xử lý xuất dữ liệu danh mục đã chọn ra file .xml
		if ($sMsg == ""){
			$sSql = 'Exec EfyLib_ListByListtypeGetAll ';
			$sSql = $sSql . "'" . $sRecordtypeId . "'";								
			$arrResult = $conn->adodbQueryDataInNameMode($sSql);
			//var_dump($arrResult);			
			//Duong dan 
			$sFilePath = '../../xml/list/output/';
			//Thuc hien Tao file xml
			createXML($sFilePath,$arrResult);
		}
		echo $sMsg;		
	}
	/**
	 * @author: HUNGVM
	 * @since : 03/02/2012
	 * @param $pFilePath : Đường dẫn lưu file đính kèm
	 * @param $arrList : Mảng danh sách đối tượng
	 */	
	function createXML($pFilePath,$arrList){
		$strXmlItem = '';
		$listTypeCode = $arrList[0]['LISTTYPE_CODE'];
		$strXml = '<?xml version="1.0" encoding="UTF-8"?><root><data_list>';
		$count = sizeof($arrList); 			
		for ($i = 0; $i < $count; $i++){
			if ($listTypeCode != $arrList[$i]['LISTTYPE_CODE']){
				$strXml .= '</data_list></root>';
				Efy_Library::_writeFile($pFilePath.$listTypeCode.'.xml',$strXml);
				$listTypeCode = $arrList[$i]['LISTTYPE_CODE'];
				$strXml = '<?xml version="1.0" encoding="UTF-8"?><root><data_list>';
			}
			$strXmlItem = '<item><c_status>'.$arrList[$i]['C_STATUS'].'</c_status><c_code>'.$arrList[$i]['C_CODE'].'</c_code><c_name>'.$arrList[$i]['C_NAME'].'</c_name><c_owner_code>'.$arrList[$i]['C_OWNERCODE'].'</c_owner_code>';
			if ($arrList[$i]['C_XML_DATA'] != ''){
				$xmlData = '<?xml version="1.0" encoding="UTF-8"?>'.$arrList[$i]['C_XML_DATA'];
				$objXmlData = new Zend_Config_Xml($xmlData,'data_list');
				$arrXmlData = $objXmlData->toArray();				
				$arrKey = array_keys($arrXmlData);				
				foreach ($arrKey As $value){
					$strXmlItem .= '<'.$value.'>'.$arrXmlData[$value].'</'.$value.'>';	
				}				
			}
			$strXmlItem .= '</item>';
			$strXml .= $strXmlItem;
		}
		$strXml .= '</data_list></root>';		
		Efy_Library::_writeFile($pFilePath.$listTypeCode.'.xml',$strXml);				
	}	
?>